"""
绘制折线图，观察流量异常情况

home_page_table.csv，首页用户访问数据
search_page_table.csv，搜索页用户访问数据
payment_page_table.csv，支付信息页用户访问数据
payment_confirmation_table.csv，支付成功页用户访问数据
user_table.csv，用户信息数据
"""

import pandas as pd
import numpy as np

from pyecharts.charts import Line
from pyecharts import options as opts
from pyecharts.charts import Page

# 1.读取数据
df_home_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/home_page_table.csv')
df_search_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/search_page_table.csv')
df_payment_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/payment_page_table.csv')
df_payment_confirmation_page = pd.read_csv('./Files/ecommerce-website-funnel-analysis/payment_confirmation_table.csv')
df_user_table = pd.read_csv('./Files/ecommerce-website-funnel-analysis/user_table.csv')

# 2.将数据合并成一个大表。合并之前各表中的重复列名修改，否则新版Python的Merge会报错
df_home_page.rename(columns={"page": "home_page"}, inplace=True)
df_search_page.rename(columns={"page": "search_page"}, inplace=True)
df_payment_page.rename(columns={"page": "payment_page"}, inplace=True)
df_payment_confirmation_page.rename(columns={"page": "confirmation_page"}, inplace=True)

df_merge = df_user_table
for df_inner in [df_home_page, df_search_page, df_payment_page, df_payment_confirmation_page]:
    df_merge = pd.merge(
        left=df_merge,
        right=df_inner,
        on='user_id',
        how='left'
    )

# print(df_merge.head())

# 3.将日期转换为时间格式
df_merge["date"] = pd.to_datetime(df_merge["date"])
# print(df_merge.info())

# 4.展现每个页面整体的PV曲线
df_data = (
    df_merge.groupby("date")
    .agg(
        pv_home_page=("home_page", lambda x: x.dropna().size),
        pv_search_page=("search_page", lambda x: x.dropna().size),
        pv_payment_page=("payment_page", lambda x: x.dropna().size),
        pv_confirmation_page=("confirmation_page", lambda x: x.dropna().size),
    )
)

# print(df_data.head())

# 5.绘制折线图
pvLine = (
    Line()
    .add_xaxis(df_data.index.to_list())
    .add_yaxis("home_page", df_data["pv_home_page"].to_list())
    .add_yaxis("search_page", df_data["pv_search_page"].to_list())
    .add_yaxis("payment_page", df_data["pv_payment_page"].to_list())
    .add_yaxis("confirmation_page", df_data["pv_confirmation_page"].to_list())
    .set_global_opts(title_opts=opts.TitleOpts(title="整体PV折线图"))
)

# 6.按设备查询search_page的问题
df_data1 = (
    df_merge.groupby(["date", "device"])["search_page"]
    .agg(pv_search_page=lambda x: x.dropna().size)
    .unstack()
)

# print(df_data1.head())

# 7.绘制折线图
pvLine1 = (
    Line()
    .add_xaxis(df_data1.index.to_list())
    .add_yaxis("Desktop", df_data1["pv_search_page", "Desktop"].to_list())
    .add_yaxis("Mobile", df_data1["pv_search_page", "Mobile"].to_list())
    .set_global_opts(title_opts=opts.TitleOpts(title="按设备查询search_page的问题"))
)

# 8.创建Page显示图表
page = Page()
page.add(pvLine, pvLine1)

# 9.生成Html
page.render('./Files/my_Line.html')
